<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page="tablePage"
      :search.sync="search"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      ref="crud"
      v-model="tableForm"
    >
      <template slot="menuLeft">
        <el-button type="primary" size="small" plain icon="el-icon-plus" @click="handleAddReport">添加 </el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot-scope="{ type, size, row, index }" slot="menu">
        <el-button icon="el-icon-view" :size="size" :type="type" @click="handleRowView(row, index)">查看详情</el-button>
        <el-button icon="el-icon-edit" :size="size" :type="type" @click="handleRowEdit(row, index)">编辑</el-button>
        <el-button icon="el-icon-delete" :size="size" :type="type" @click="handleRowDelete(row, index)">删除</el-button>
      </template>
    </avue-crud>

    <el-dialog :title="dialogTitle" append-to-body :visible.sync="dialogVisible" width="960">
      <div class="sail-header-dialog-content">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="基础数据" name="base">
            <base-info-form :key="timer" ref="baseInfoForm" @baseInfoChange="handleBaseInfoChange" :form-data="editForm" :isViewStatus="isViewStatus"></base-info-form>
          </el-tab-pane>
          <el-tab-pane label="数据源" name="datasource">
            <data-source-form
              :key="timer"
              v-if="activeName === 'datasource'"
              ref="dataSourceForm"
              @dataBaseChange="handleDataBaseChange"
              @dataSourceChange="handleDataSourceChange"
              :form-data="editForm.reportSql"
              :data-source="editForm.datasourceName"
              :is-view-status="isViewStatus"
            ></data-source-form>
          </el-tab-pane>
          <!--        <el-tab-pane label="表格基础数据" name="tableConfig">-->
          <!--          <avue-form :option="baseOption" v-if="activeName === 'tableConfig'" v-model="editForm.optionJson"></avue-form>-->
          <!--        </el-tab-pane>-->
          <el-tab-pane label="表格查询参数" name="tableQuery">
            <table-query v-if="activeName === 'tableQuery'" :is-view-status="isViewStatus" :form-data="editForm.reportQueryList" @change="handleAddQuery"></table-query>
          </el-tab-pane>
          <el-tab-pane label="表格列名展示" name="tableColumn">
            <!--            :class="{ 'pop-container': isViewStatus }"-->
            <table-column v-if="activeName === 'tableColumn'" :is-view-status="isViewStatus" :form-data="editForm.optionJson.columnDefs" @change="handleAddCol"></table-column>
          </el-tab-pane>
          <!--         不知道具体作用先注释-->
          <!--        <el-tab-pane label="表格功能配置" name="tableFunctionConfig">-->
          <!--          <tablefunction-config></tablefunction-config>-->
          <!--        </el-tab-pane>-->
        </el-tabs>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleCancel">取 消</el-button>
        <el-button type="primary" size="small" @click="handleSubmit" :disabled="isViewStatus" :loading="addLoading"> 确 定</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import baseInfoForm from './reportConfigComponent/baseInfoForm';
import dataSourceForm from './reportConfigComponent/dataSourceForm';
import tableQuery from './reportConfigComponent/tableQuery';
import TableColumn from '@/views/report/reportConfigComponent/tableColumn';
import TablefunctionConfig from '@/views/report/reportConfigComponent/tablefunctionConfig';
import { addReportConfig, deleteReportConfig, getDataSourceName, getReportConfig, viewReportConfig } from '@/api/admin/reportConfig';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  name: 'reportConfig',
  components: {
    TablefunctionConfig,
    TableColumn,
    baseInfoForm,
    dataSourceForm,
    tableQuery,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'REPORT_CONFIG',
      dialogTitle: '新增',
      dialogVisible: false,
      addLoading: false,
      loading: false,
      activeName: 'base',
      timer: new Date().getTime(),
      editForm: {
        reportSql: {},
        reportQueryList: [],
        optionJson: { columnDefs: [] },
        paginationPageSize: 10,
        pagination: true
      },
      isViewStatus: false,
      tablePage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      data: [],
      baseOption: {
        menuPosition: 'right',
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '是否分页',
            span: 12,
            labelWidth: 150,
            prop: 'pagination',
            type: 'switch',
            value: true
          },
          {
            span: 12,
            labelWidth: 150,
            label: '分页条数',
            prop: 'paginationPageSize',
            value: 10
          }
        ]
      },
      tableForm: {},
      search: {},
      option: {
        height: 'calc(100vh - 440px)',
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        menu: true,
        columnBtn: false,
        column: [
          {
            label: '报表名称',
            prop: 'zhCnName',
            search: true
          },
          {
            label: '报表id',
            prop: 'id',
            width: 150
          },
          {
            label: '报表编码',
            prop: 'code'
          },
          {
            label: '报表类型',
            prop: 'type',
            formatter: ({ type }) => {
              const typeMap = {
                GRID: '报表'
              };
              return typeMap[type];
            }
          },
          {
            label: '报表模块',
            prop: 'module',
            formatter: ({ module }) => {
              const moduleMap = {
                REPORT: '报表'
              };
              return moduleMap[module];
            }
          },
          {
            label: 'url地址',
            prop: 'url'
          },
          {
            label: '序号',
            prop: 'sequence'
          },
          {
            label: '是否启用',
            prop: 'enabled',
            formatter: ({ enabled }) => {
              return enabled ? '是' : '否';
            }
          },
          {
            label: '备注',
            prop: 'zhCnContent'
          },
          {
            label: '生成日期',
            prop: 'createTime'
          }
        ]
      }
    };
  },
  async mounted() {
    await this.onLoad();
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
    });
  },
  methods: {
    async onLoad() {
      this.loading = true;
      const params = {
        current: this.tablePage.currentPage,
        size: this.tablePage.pageSize,
        zhCnName: this.search.zhCnName
      };
      try {
        const res = await getReportConfig(params);
        const data = res.data.data;
        this.data = data.records;
        this.tablePage = {
          pageSize: data.size,
          currentPage: data.current,
          total: data.total
        };
      } catch (e) {
        console.warn(e);
      } finally {
        this.loading = false;
      }
    },
    searchReset() {
      this.tablePage = {
        pageSize: 20,
        currentPage: 1
      };
      this.onLoad();
    },
    searchChange(params, done) {
      this.tablePage = {
        pageSize: 20,
        currentPage: 1
      };
      this.onLoad();
      done();
    },
    async addReport(done) {
      try {
        this.editForm.optionJson = typeof this.editForm.optionJson === 'string' ? this.editForm.optionJson : JSON.stringify(this.editForm.optionJson);
        let formTemp = this._cloneDeep(this.editForm.reportQueryList).map((item) => {
          return { ...item };
        });
        this.editForm.reportQueryList = formTemp;
        delete this.editForm.reportSql.datasourceName;
        const params = this.editForm;
        this.addLoading = true;
        await addReportConfig(params);
        this.$message.success('操作成功');
        this.dialogVisible = true;
        this.editForm = {
          reportSql: {},
          reportQueryList: [],
          optionJson: {
            paginationPageSize: 10,
            pagination: true,
            columnDefs: []
          }
        };
        this.dialogVisible = false;
        this.onLoad();
      } catch (e) {
        done();
        console.warn(e);
      } finally {
        this.addLoading = false;
      }
    },
    handleAddReport() {
      this.dialogTitle = '新增';
      this.activeName = 'base';
      this.isViewStatus = false;
      this.timer = new Date().getTime();
      this.dialogVisible = true;
      this.editForm = {
        reportSql: {},
        reportQueryList: [],
        optionJson: { columnDefs: [] },
        paginationPageSize: 10,
        pagination: true,
        module: 'REPORT',
        type: 'GRID',
        isDefaultLoad: true,
        enabled: true
      };
    },
    handleClick() {},
    handleBaseInfoChange(form) {
      const reportSql = this.editForm.reportSql;
      Object.assign(this.editForm, form, { reportSql });
    },
    handleDataSourceChange(form) {
      Object.assign(this.editForm.reportSql, {}, form);
    },
    handleDataBaseChange({ datasourceName, datasourceId }) {
      this.$set(this.editForm, 'datasourceId', datasourceId);
      this.$set(this.editForm, 'datasourceName', datasourceName);
    },
    handleCancel() {
      this.isViewStatus = false;
      this.dialogVisible = false;
    },
    handleSubmit() {
      this.$refs.baseInfoForm.$refs.form.validate((valid, done) => {
        if (valid) {
          // done();
          if (this.editForm.datasourceId) {
            this.addReport(done);
          } else {
            this.activeName = 'datasource';
            setTimeout(() => {
              this.$refs.dataSourceForm.formValidate();
            });
          }
          done();
        } else {
          this.activeName = 'base';
        }
      });
    },
    handleAddQuery(data) {
      this.$set(this.editForm, 'reportQueryList', data);
    },
    handleAddCol(form) {
      this.editForm.optionJson.columnDefs = form;
    },
    async handleRowView(row, index) {
      this.dialogTitle = '详情';
      this.isViewStatus = true;
      this.activeName = 'base';
      this.setBaseInfoTableCol();
      this.getRowData(row);
    },
    async handleRowEdit(row, index) {
      this.dialogTitle = '编辑';
      this.isViewStatus = false;
      this.activeName = 'base';
      this.setBaseInfoTableCol();
      this.getRowData(row);
    },
    // 获取当前行的数据
    async getRowData(row) {
      try {
        const res = await viewReportConfig({ id: row.id });
        const datasourceName = await this.getDataSourceShowName(row);
        const data = res.data.data;
        const optionJson = JSON.parse(data.optionJson);
        this.editForm = {
          reportSql: data.reportSql || {},
          reportQueryList: data.reportQueryList || [],
          datasourceName,
          ...data
        };
        // 层级过深 导致响应式被丢失
        this.$set(this.editForm, 'optionJson', optionJson);
        this.dialogVisible = true;
      } catch (e) {
        console.warn(e);
      }
    },
    async handleRowDelete(row, index) {
      try {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const res = await deleteReportConfig([row.id]);
          this.$message.success('删除成功');
          this.onLoad();
        });
      } catch (e) {
        console.warn(e);
      }
    },
    async getDataSourceShowName(row) {
      try {
        if (row.datasourceId) {
          const res = await getDataSourceName({ id: row.datasourceId });
          return res.data.data.name;
        } else {
          return '';
        }
      } catch (e) {
        console.warn(e);
      }
    },

    setBaseInfoTableCol() {
      const column = this._cloneDeep(this.baseOption.column).map((item) => {
        return {
          ...item,
          disabled: this.isViewStatus
        };
      });
      this.$set(this.baseOption, 'column', column);
    },
    currentChange(currentPage) {
      this.tablePage.currentPage = currentPage;
      this.onLoad();
    },
    sizeChange(pageSize) {
      this.tablePage.pageSize = pageSize;
      this.onLoad();
    }
  }
};
</script>

<style scoped lang="scss"></style>
